//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//********************************************************* 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using Microsoft.TridentWordAddIn.Common;
using Microsoft.TridentWordAddIn.ResourceHelper;
using Microsoft.TridentWordAddIn.Server;

namespace Microsoft.TridentWordAddIn.Presentation
{
    /// <summary>
    /// Class representing form for creating or editing connection.
    /// </summary>
    internal partial class ConnectionForm : BaseForm
    {
        #region Member Variables

        private ConnectionXmlReader connectionHelper;
        private UserControl ctrAccountInformation;
        private UserControl ctrStoreInformation;
        private TridentConnection connection;
        private TridentConnection orginalConnection;
        private bool isConnectionSuccessful;
        private bool cancelClosing = false;        
        private bool deleteOnCancel;
        private bool savedDeleteOnCancel = false;
        private IController controller;
        private bool editMode = false;
        private bool isTempConnection = false;

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ConnectionForm"/> class.
        /// </summary>
        /// <param name="editConnection">The edit connection.</param>
        /// <param name="isTempConnection">if set to <c>true</c> [is temp connection].</param>
        public ConnectionForm(ref TridentConnection editConnection, bool isTempConnection) 
            : this(ref editConnection, true, false, isTempConnection)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ConnectionForm"/> class.
        /// </summary>
        /// <param name="editConnection">The edit connection.</param>
        /// <param name="editMode">if set to <c>true</c> [edit mode].</param>
        /// <param name="deleteOnCancel">if set to <c>true</c> [delete on cancel].</param>
        /// <param name="isTempConnection">if set to <c>true</c> [is temp connection].</param>
        public ConnectionForm(ref TridentConnection editConnection, bool editMode, bool deleteOnCancel, bool isTempConnection)
        {
            this.InitializeComponent();
            this.connectionHelper = new ConnectionXmlReader();
            string selectedDataSource = null;
            this.deleteOnCancel = deleteOnCancel;
            this.controller = Controller.Instance(null);
            this.orginalConnection = editConnection;
            this.editMode = editMode;
            this.isTempConnection = isTempConnection;

            this.SetDefaultConnectionChkBox(editMode);

            if (!this.IsCredentialEmpty())
            {
                int formHeight = this.Height - this.pnlMessage.Height;
                this.pnlMessage.Visible = false;
                this.Size = new System.Drawing.Size(this.Width, formHeight);
            }
            else
            {
                this.lblMessage.Text = ResourceFetcher.GetString("CredentialRequired");
            }

            if (editConnection == null)
            {
                selectedDataSource = this.connectionHelper.GetSelectedSourceName();
                editConnection = new TridentConnection();
            }
            else
            {
                this.cmbSource.Enabled = false;
            }

            this.connection = editConnection.Clone() as TridentConnection;
            selectedDataSource = selectedDataSource ?? this.connection.SourceName;
            this.InitializeSourceComboBox(selectedDataSource);
        }

        #endregion

        /// <summary>
        /// Sets the default connection.
        /// </summary>
        /// <param name="editMode">if set to <c>true</c> [edit mode].</param>
        private void SetDefaultConnectionChkBox(bool editMode)
        {
            int connectionCount = this.controller.UserData.Connections.Count;
            this.chkMakeDefaultConnection.Enabled = !((!editMode && connectionCount == 0)||
                                                    (editMode && connectionCount == 1) ||
                                                    (editMode && 
                                                     this.orginalConnection.Name.Compare(this.controller.CurrentConnectionName)));         
        }

        #region Properties

        /// <summary>
        /// Gets the connection.
        /// </summary>
        /// <value>The connection.</value>
        public TridentConnection Connection
        {
            get { return this.connection; }
        }

        /// <summary>
        /// Gets a value indicating whether this instance is connection successful.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if this instance is connection successful; otherwise, <c>false</c>.
        /// </value>
        public bool IsConnectionSuccessfull
        {
            get { return this.isConnectionSuccessful; }
        }       
        
        #endregion                

        #region Event Handlers

        /// <summary>
        /// Handles the SelectedValueChanged event of the cmbSource control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void cmbSource_SelectedValueChanged(object sender, EventArgs e)
        {
            this.SuspendLayout();
            string selectedDataSource = this.cmbSource.SelectedItem.ToString();
            this.SetDataSourceControls(selectedDataSource);
            this.ResumeLayout();
        }

        /// <summary>
        /// Called when [validation].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="Microsoft.TridentWordAddIn.Common.ConnectionValidateEventArgs"/> instance containing the event data.</param>
        private void OnValidation(object sender, ConnectionValidateEventArgs e)
        {
            switch (e.ControlType)
            {
                case "TextBox":
                    this.errorProvider.SetError(sender as TextBox, e.Message);
                    break;
                case "ComboBox":
                    this.errorProvider.SetError(sender as ComboBox, e.Message);
                    break;
            }
        }      

        /// <summary>
        /// Handles the Click event of the btnTestConnection control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void btnTestConnection_Click(object sender, EventArgs e)
        {
            ValidationResult result = this.IsValid();

            if (!result.IsValid)
            {
                string message = result.GetMessage();
                MessageBoxHelper.ShowDefault(message, MessageBoxIcon.Exclamation);
                return;
            }

            ConnectionFailedException connectionFailedException = null;
            if (this.TestConnection(ref connectionFailedException))
            {
                MessageBoxHelper.ShowDefault(ResourceFetcher.GetString("TestConnectionSuccess"));
            }
            else
            {
                string errorMessage = connectionFailedException.Message + "\n\n" + connectionFailedException.InnerException.Message;
                MessageBoxHelper.ShowDefault(errorMessage, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// Handles the Click event of the btnOK control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void btnOK_Click(object sender, EventArgs e)
        {
            bool isDefaultConnection = false;
            bool isOverWriteConnection = false;
            ValidationResult result = this.IsValid();
            if (!result.IsValid)
            {
                string message = result.GetMessage();
                MessageBoxHelper.ShowDefault(message, MessageBoxIcon.Exclamation);
                this.savedDeleteOnCancel = this.deleteOnCancel;
                this.deleteOnCancel = false;
                this.cancelClosing = true;
                return;
            }

            ConnectionFailedException connectionFailedException = null;
            this.isConnectionSuccessful = this.TestConnection(ref connectionFailedException);
            if (!this.isConnectionSuccessful)
            {
                string errorMessage = connectionFailedException.Message + "\n\n";
                if (connectionFailedException.InnerException != null)
                {
                    errorMessage += connectionFailedException.InnerException.Message;
                }

                MessageBoxHelper.ShowDefault(errorMessage, MessageBoxIcon.Error);
                this.cancelClosing = true;
                this.savedDeleteOnCancel = this.deleteOnCancel;
                this.deleteOnCancel = false;
                return;
            }

            isDefaultConnection = this.chkMakeDefaultConnection.Checked && !this.isTempConnection;
            if (this.IsConnectionNameExists())
            {
                string confirmationMessage = string.Format(
                    ResourceFetcher.GetString("OverwriteConnectionConfirmation"),
                    this.connection.Name);
                if (MessageBoxHelper.ShowYesNo(confirmationMessage) == DialogResult.Yes)
                {
                    isOverWriteConnection = true;
                }
                else
                {
                    this.isConnectionSuccessful = false;
                    this.cancelClosing = true;
                    this.savedDeleteOnCancel = this.deleteOnCancel;
                    this.deleteOnCancel = false;
                    return;
                }
            }

            this.connection.NeedCredentialSave = this.NeedCredentialSave() && !this.isTempConnection;
            if (this.deleteOnCancel)
            {
                this.deleteOnCancel = this.connection.NeedCredentialSave;
            }

            if (this.connection.NeedCredentialSave)
            {             
                if (MessageBoxHelper.ShowYesNo(ResourceFetcher.GetString("SaveCredentialConfirmation")) == DialogResult.No)
                {
                    this.connection.NeedCredentialSave = false;
                }

                this.deleteOnCancel = false;
            }

            if (this.isConnectionSuccessful)
            {
                this.ConnectionSucceeded(isDefaultConnection, isOverWriteConnection);
            }
        }               
        
        /// <summary>
        /// Handles the OnDatabaseClicked event of the ctrSqlStoreInformation control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Microsoft.TridentWordAddIn.Common.DatabaseClickedEventArgs"/> instance containing the event data.</param>
        private void ctrSqlStoreInformation_OnDatabaseClicked(object sender, DatabaseClickedEventArgs e)
        {
            SqlAccountInformation accountInformation = this.ctrAccountInformation as SqlAccountInformation;
            List<string> databaseList = ConnectionHelper.GetSqlDatabaseList(
                accountInformation.IsTrusted,
                accountInformation.ServerName,
                accountInformation.UserName,
                accountInformation.Password);

            e.DatabaseList = databaseList.ToArray();
        }

        /// <summary>
        /// Handles the Load event of the ConnectionForm control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void ConnectionForm_Load(object sender, EventArgs e)
        {
            this.txtConnectionName.Text = this.connection.Name;
            switch (this.connection.ConnectionType)
            {
                case ConnectionType.AmazonWebService:
                    this.PopulateUIFromTridentConnection(
                        this.ctrAccountInformation as WebServiceAccountInformation,
                        this.ctrStoreInformation as WebServiceStoreInformation);
                    break;
                case ConnectionType.Sitka:
                    this.PopulateUIFromTridentConnection(
                        this.ctrAccountInformation as CloudDatabaseAccountInformation,
                        this.ctrStoreInformation as CloudDatabaseStoreInformation);
                    break;
                case ConnectionType.Sql:
                    this.PopulateUIFromTridentConnection(
                        this.ctrAccountInformation as SqlAccountInformation,
                        this.ctrStoreInformation as SqlStoreInformation);
                    break;
                case ConnectionType.WebService:
                    this.PopulateUIFromTridentConnection(this.ctrAccountInformation as WebServiceConnection);
                    break;
            }
        }

        /// <summary>
        /// Handles the Validating event of the txtConnectionName control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.ComponentModel.CancelEventArgs"/> instance containing the event data.</param>
        private void txtConnectionName_Validating(object sender, CancelEventArgs e)
        {
            ValidationResult result = this.IsValidConnectionName();
            ConnectionValidateEventArgs connectionEventArgs = new ConnectionValidateEventArgs(result.GetMessage(), result.IsValid, "TextBox");
            this.OnValidation(sender, connectionEventArgs);
        }

        /// <summary>
        /// Handles the FormClosing event of the ConnectionForm control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.FormClosingEventArgs"/> instance containing the event data.</param>
        private void ConnectionForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.deleteOnCancel)
            {               
                if (MessageBoxHelper.ShowYesNo(ResourceFetcher.GetString("ConnectionDeletionWarningOnCancel")) == DialogResult.No)
                {
                    e.Cancel = true;
                }               
            }

            if (this.savedDeleteOnCancel)
            {
                this.deleteOnCancel = true;
                this.savedDeleteOnCancel = false;
            }

            if (this.cancelClosing)
            {
                e.Cancel = true;
            }

            this.cancelClosing = false;
        }       

        #endregion

        #region Private Members

        /// <summary>
        /// Initializes the source combo box.
        /// </summary>
        /// <param name="selectedDataSource">The selected data source.</param>
        private void InitializeSourceComboBox(string selectedDataSource)
        {
            this.cmbSource.DataSource = this.connectionHelper.GetDataSources();
            this.cmbSource.SelectedValueChanged += new EventHandler(cmbSource_SelectedValueChanged);
            if (selectedDataSource != null)
            {
                this.cmbSource.SelectedItem = selectedDataSource;
                this.cmbSource_SelectedValueChanged(this.cmbSource, null);

            }
        }

        /// <summary>
        /// Sets the data source controls.
        /// </summary>
        /// <param name="selectedDataSource">The selected data source.</param>
        private void SetDataSourceControls(string selectedDataSource)
        {
            this.pnlAcountInformation.Controls.Clear();
            this.ctrAccountInformation = this.connectionHelper.GetControlObject(selectedDataSource, "AccountType");
            this.pnlAcountInformation.Controls.Add(this.ctrAccountInformation);

            this.pnlStorageInformation.Controls.Clear();
            this.ctrStoreInformation = this.connectionHelper.GetControlObject(selectedDataSource, "StorageType");
            this.pnlStorageInformation.Controls.Add(this.ctrStoreInformation);

            this.AccountStoreEventHandlers(selectedDataSource);
        }

        /// <summary>
        /// Accounts the store event handlers.
        /// </summary>
        /// <param name="selectedDataSource">The selected data source.</param>
        private void AccountStoreEventHandlers(string selectedDataSource)
        {
            string dataSourceType = this.connectionHelper.GetDataSourceType(selectedDataSource);
            switch (dataSourceType)
            {
                case "AmazonWebService":
                    WebServiceAccountInformation ctrWebServiceAccountInformation = this.ctrAccountInformation as WebServiceAccountInformation;
                    ctrWebServiceAccountInformation.OnValidation += new EventHandler<ConnectionValidateEventArgs>(OnValidation);

                    WebServiceStoreInformation ctrWebServiceStoreInformation = this.ctrStoreInformation as WebServiceStoreInformation;
                    ctrWebServiceStoreInformation.OnValidation += new EventHandler<ConnectionValidateEventArgs>(OnValidation);
                    break;
                case "Sitka":
                    CloudDatabaseAccountInformation ctrCloudDatabaseAccountInformation = this.ctrAccountInformation as CloudDatabaseAccountInformation;
                    ctrCloudDatabaseAccountInformation.OnValidation += new EventHandler<ConnectionValidateEventArgs>(OnValidation);

                    CloudDatabaseStoreInformation ctrCloudDatabaseStoreInformation = this.ctrStoreInformation as CloudDatabaseStoreInformation;
                    ctrCloudDatabaseStoreInformation.OnValidation += new EventHandler<ConnectionValidateEventArgs>(OnValidation);
                    break;
                case "SQL":
                    SqlAccountInformation ctrSqlAccountInformation = this.ctrAccountInformation as SqlAccountInformation;
                    ctrSqlAccountInformation.OnValidation += new EventHandler<ConnectionValidateEventArgs>(OnValidation);

                    SqlStoreInformation ctrSqlStoreInformation = this.ctrStoreInformation as SqlStoreInformation;
                    ctrSqlStoreInformation.OnValidation += new EventHandler<ConnectionValidateEventArgs>(OnValidation);
                    ctrSqlStoreInformation.OnDatabaseClicked += new EventHandler<DatabaseClickedEventArgs>(ctrSqlStoreInformation_OnDatabaseClicked);
                    break;
                case "WebService":
                    WebServiceConnection ctrWebService = this.ctrAccountInformation as WebServiceConnection;
                    ctrWebService.OnValidation += new EventHandler<ConnectionValidateEventArgs>(OnValidation);
                    break;
            }
        }

        /// <summary>
        /// Tests the connection.
        /// </summary>
        /// <param name="connectionFailedException">The connection failed exception.</param>
        /// <returns>bool</returns>
        private bool TestConnection(ref ConnectionFailedException connectionFailedException)
        {
            Cursor.Current = Cursors.WaitCursor;
            bool success = false;
            this.GetTridentConnection(this.connection);
            if (TridentServer.TestConnection(this.connection, ref connectionFailedException))
            {
                success = true;
            }

            Cursor.Current = Cursors.Default;
            return success;
        }

        /// <summary>
        /// Determines whether this instance is valid.
        /// </summary>
        /// <returns>ValidationResult</returns>
        private ValidationResult IsValid()
        {
            string selectedDataSource = this.cmbSource.SelectedItem.ToString();
            string dataSourceType = this.connectionHelper.GetDataSourceType(selectedDataSource);
            ValidationResult result = this.IsValidConnectionName();

            switch (dataSourceType)
            {
                case "AmazonWebService":
                    WebServiceAccountInformation ctrWebServiceAccountInformation = this.ctrAccountInformation as WebServiceAccountInformation;
                    WebServiceStoreInformation ctrWebServiceStoreInformation = this.ctrStoreInformation as WebServiceStoreInformation;
                    result.Merge(ctrWebServiceAccountInformation.IsValid());
                    result.Merge(ctrWebServiceStoreInformation.IsValid());
                    break;
                case "Sitka":
                    CloudDatabaseAccountInformation ctrCloudDatabaseAccountInformation = this.ctrAccountInformation as CloudDatabaseAccountInformation;
                    CloudDatabaseStoreInformation ctrCloudDatabaseStoreInformation = this.ctrStoreInformation as CloudDatabaseStoreInformation;
                    result.Merge(ctrCloudDatabaseAccountInformation.IsValid());
                    result.Merge(ctrCloudDatabaseStoreInformation.IsValid());
                    break;
                case "SQL":
                    SqlAccountInformation ctrSqlAccountInformation = this.ctrAccountInformation as SqlAccountInformation;
                    SqlStoreInformation ctrSqlStoreInformation = this.ctrStoreInformation as SqlStoreInformation;
                    result.Merge(ctrSqlAccountInformation.IsValid());
                    result.Merge(ctrSqlStoreInformation.IsValid());
                    break;
                case "WebService":
                    WebServiceConnection ctrWebService = this.ctrAccountInformation as WebServiceConnection;
                    result.Merge(ctrWebService.IsValid());
                    break;
            }

            return result;
        }

        /// <summary>
        /// Determines whether [is connection name exists].
        /// </summary>
        /// <returns>
        /// 	<c>true</c> if [is connection name exists]; otherwise, <c>false</c>.
        /// </returns>
        private bool IsConnectionNameExists()
        {
            bool isExists = false;
            string newConnectionName = this.connection.Name;
            string orginalConnectionName = this.orginalConnection != null ? this.orginalConnection.Name : null;
            Dictionary<string, TridentConnection>.KeyCollection keyCollection = this.controller.UserData.Connections.Keys;
            foreach (string key in keyCollection)
            {
                if (key.CompareIgnoreCase(newConnectionName))
                {
                    isExists = true;
                    break;
                }
            }
           
            if (isExists &&
                !orginalConnectionName.IsNullOrEmpty() &&
                newConnectionName.CompareIgnoreCase(orginalConnectionName))
            {
                isExists = false;
            }

            return isExists;
        }

        /// <summary>
        /// Gets the trident connection object.
        /// </summary>
        /// <param name="tridentConnection">The trident connection.</param>
        /// <returns>TridentConnection</returns>
        private TridentConnection GetTridentConnection(TridentConnection tridentConnection)
        {
            string selectedDataSource = this.cmbSource.SelectedItem.ToString();
            this.connection.SourceName = selectedDataSource;
            this.connection.Name = this.txtConnectionName.Text;
            string dataSourceType = this.connectionHelper.GetDataSourceType(selectedDataSource);
            switch (dataSourceType)
            {
                case "AmazonWebService":
                    tridentConnection.ConnectionType = ConnectionType.AmazonWebService;
                    this.PopulateTridentConnection(
                        this.ctrAccountInformation as WebServiceAccountInformation,
                        this.ctrStoreInformation as WebServiceStoreInformation);
                    break;
                case "Sitka":
                    tridentConnection.ConnectionType = ConnectionType.Sitka;
                    this.PopulateTridentConnection(
                        this.ctrAccountInformation as CloudDatabaseAccountInformation,
                        this.ctrStoreInformation as CloudDatabaseStoreInformation);
                    break;
                case "SQL":
                    tridentConnection.ConnectionType = ConnectionType.Sql;
                    this.PopulateTridentConnection(
                        this.ctrAccountInformation as SqlAccountInformation,
                        this.ctrStoreInformation as SqlStoreInformation);
                    break;
                case "WebService":
                    tridentConnection.ConnectionType = ConnectionType.WebService;
                    this.PopulateTridentConnection(
                        this.ctrAccountInformation as WebServiceConnection);
                    break;
            }

            return tridentConnection;
        }

        /// <summary>
        /// Determines whether [is valid connection name].
        /// </summary>
        /// <returns>ValidationResult</returns>
        private ValidationResult IsValidConnectionName()
        {
            ValidationResult result = new ValidationResult(!this.txtConnectionName.Text.Trim().IsNullOrEmpty());
            if (!result.IsValid)
            {
                result.Messages.Add("Connection name is required");
            }

            return result;
        }

        /// <summary>
        /// Needs the credential save.
        /// </summary>
        /// <returns>bool</returns>
        private bool NeedCredentialSave()
        {
            bool needCredentialSave = false;
            switch (this.connection.ConnectionType)
            {
                case ConnectionType.Sql:
                    needCredentialSave = !this.connection.SqlParameters.IsTrusted;
                    break;
                case ConnectionType.Sitka:
                    needCredentialSave = true;
                    break;
                case ConnectionType.AmazonWebService:
                    needCredentialSave = true;
                    break;
                case ConnectionType.WebService:
                    needCredentialSave = !this.Connection.WebServiceParameters.IsAnonymous;
                    break;
            }

            return needCredentialSave;
        }

        /// <summary>
        /// Connections the succeeded.
        /// </summary>
        /// <param name="isDefaultConnection">if set to <c>true</c> [is default connection].</param>
        /// <param name="isOverwriteConnection">if set to <c>true</c> [is overwrite connection].</param>
        private void ConnectionSucceeded(bool isDefaultConnection, bool isOverwriteConnection)
        {
            if (isOverwriteConnection)
            {
                this.controller.RemoveConnection(this.Connection.Name);
                string currentConnection = this.controller.UserData.CurrentConnectionName;
                if (!currentConnection.IsNullOrEmpty() &&
                    currentConnection.Compare(this.Connection.Name))
                {
                    isDefaultConnection = true;
                }
            }

            if (this.editMode)
            {
                this.EditConnection(isDefaultConnection);
            }
            else
            {
                if (isDefaultConnection)
                {
                    this.controller.CurrentConnection = this.Connection;
                    this.controller.ConnectionChanged(isDefaultConnection, ConnectionOperation.Changed);
                }
                else
                {
                    this.controller.UserData.Connections.Add(this.Connection.Name, this.Connection);
                    this.controller.ConnectionChanged(isDefaultConnection, ConnectionOperation.Added);
                }
            }
        }

        /// <summary>
        /// Edits the connection.
        /// </summary>
        /// <param name="isDefaultConnection">if set to <c>true</c> [is default connection].</param>
        private void EditConnection(bool isDefaultConnection)
        {
            if (!this.isTempConnection)
            {
                string orginalConnectionName = this.orginalConnection.Name;
                this.controller.RemoveConnection(orginalConnectionName);
                this.controller.UserData.Connections.Add(this.Connection.Name, this.Connection);
                string currentConnectionName = this.controller.UserData.CurrentConnectionName;
                if ((!currentConnectionName.IsNullOrEmpty() && currentConnectionName.Compare(orginalConnectionName)) ||
                     isDefaultConnection)
                {
                    this.controller.UserData.CurrentConnectionName = this.Connection.Name;
                    this.controller.CurrentConnection = this.Connection;
                    this.controller.ConnectionChanged(isDefaultConnection, ConnectionOperation.Changed);
                }
                else
                {
                    this.controller.ConnectionChanged(isDefaultConnection, ConnectionOperation.Edited);
                }
            }
        }

        /// <summary>
        /// Determines whether [is credential empty].
        /// </summary>
        /// <returns>
        /// 	<c>true</c> if [is credential empty]; otherwise, <c>false</c>.
        /// </returns>
        private bool IsCredentialEmpty()
        {
            bool isCredentialEmpty = false;

            if (this.orginalConnection != null)
            {
                switch (this.orginalConnection.ConnectionType)
                {
                    case ConnectionType.Sql:
                        isCredentialEmpty = !this.orginalConnection.SqlParameters.IsTrusted &&
                                             this.orginalConnection.SqlParameters.Password.IsNullOrEmpty();
                        break;
                    case ConnectionType.Sitka:
                        isCredentialEmpty = this.orginalConnection.SitkaParameters.Password.IsNullOrEmpty();
                        break;
                    case ConnectionType.AmazonWebService:
                        isCredentialEmpty = this.orginalConnection.AmazonParameters.SecretKey.IsNullOrEmpty();
                        break;
                }
            }

            return isCredentialEmpty;
        }

        #region PopulateTridentConnection functions

        /// <summary>
        /// Populates the trident connection.
        /// </summary>
        /// <param name="ctrSqlAccountInformation">The CTR SQL account information.</param>
        /// <param name="ctrSqlStoreInformation">The CTR SQL store information.</param>
        private void PopulateTridentConnection(SqlAccountInformation ctrSqlAccountInformation, SqlStoreInformation ctrSqlStoreInformation)
        {
            this.connection.SqlParameters = new TridentSqlConnectionParameters();
            this.connection.SqlParameters.ServerName = ctrSqlAccountInformation.ServerName;
            this.connection.SqlParameters.IsTrusted = ctrSqlAccountInformation.IsTrusted;
            if (!this.connection.SqlParameters.IsTrusted)
            {
                this.connection.SqlParameters.UserName = ctrSqlAccountInformation.UserName;
                this.connection.SqlParameters.Password = ctrSqlAccountInformation.Password;
            }
            this.connection.SqlParameters.DatabaseName = ctrSqlStoreInformation.DatabaseName;
        }

        /// <summary>
        /// Populates the trident connection.
        /// </summary>
        /// <param name="ctrCloudDatabaseAccountInformation">The CTR cloud database account information.</param>
        /// <param name="ctrCloudDatabaseStoreInformation">The CTR cloud database store information.</param>
        private void PopulateTridentConnection(CloudDatabaseAccountInformation ctrCloudDatabaseAccountInformation, CloudDatabaseStoreInformation ctrCloudDatabaseStoreInformation)
        {
            this.connection.SitkaParameters = new TridentSitkaConnectionParameters();
            this.connection.SitkaParameters.AuthorityId = ctrCloudDatabaseStoreInformation.AuthorityId;
            this.connection.SitkaParameters.ContainerId = ctrCloudDatabaseStoreInformation.ContainerId;
            this.connection.SitkaParameters.UserName = ctrCloudDatabaseAccountInformation.UserName;
            this.connection.SitkaParameters.Password = ctrCloudDatabaseAccountInformation.Password;
        }

        /// <summary>
        /// Populates the trident connection.
        /// </summary>
        /// <param name="ctrWebServiceAccountInformation">The CTR web service account information.</param>
        /// <param name="ctrWebServiceStoreInformation">The CTR web service store information.</param>
        private void PopulateTridentConnection(WebServiceAccountInformation ctrWebServiceAccountInformation, WebServiceStoreInformation ctrWebServiceStoreInformation)
        {
            this.connection.AmazonParameters = new TridentWebServiceConnectionParameters();
            this.connection.AmazonParameters.AccessKey = ctrWebServiceAccountInformation.AccessKeyId;
            this.connection.AmazonParameters.SecretKey = ctrWebServiceAccountInformation.SecretAccessKey;
            this.connection.AmazonParameters.PublicObjects = ctrWebServiceAccountInformation.IsPublicObject;
            this.connection.AmazonParameters.Bucket = ctrWebServiceStoreInformation.Bucket;
        }

        /// <summary>
        /// Populates the trident connection.
        /// </summary>
        /// <param name="ctrWebService">The CTR web service.</param>
        private void PopulateTridentConnection(WebServiceConnection ctrWebService)
        {
            this.connection.WebServiceParameters = new WebServiceParameters();
            this.connection.WebServiceParameters.IsAnonymous = ctrWebService.IsAnonymous;
            this.connection.WebServiceParameters.UserName = ctrWebService.UserName;
            this.connection.WebServiceParameters.Password = ctrWebService.Password;
            this.connection.WebServiceParameters.Url = ctrWebService.Url;
        }

        #endregion

        #region PoupluateUIFromTridentConnection functions

        /// <summary>
        /// Populates the UI from trident connection.
        /// </summary>
        /// <param name="ctrSqlAccountInformation">The CTR SQL account information.</param>
        /// <param name="ctrSqlStoreInformation">The CTR SQL store information.</param>
        private void PopulateUIFromTridentConnection(SqlAccountInformation ctrSqlAccountInformation, SqlStoreInformation ctrSqlStoreInformation)
        {
            TridentSqlConnectionParameters sqlConnectionParameters = this.connection.SqlParameters;
            if (sqlConnectionParameters != null)
            {
                ctrSqlAccountInformation.ServerName = sqlConnectionParameters.ServerName;
                ctrSqlAccountInformation.IsTrusted = sqlConnectionParameters.IsTrusted;
                ctrSqlAccountInformation.UserName = sqlConnectionParameters.UserName;
                ctrSqlAccountInformation.Password = sqlConnectionParameters.Password;
                ctrSqlStoreInformation.DatabaseName = sqlConnectionParameters.DatabaseName;
            }
        }

        /// <summary>
        /// Populates the UI from trident connection.
        /// </summary>
        /// <param name="ctrCloudDatabaseAccountInformation">The CTR cloud database account information.</param>
        /// <param name="ctrCloudDatabaseStoreInformation">The CTR cloud database store information.</param>
        private void PopulateUIFromTridentConnection(CloudDatabaseAccountInformation ctrCloudDatabaseAccountInformation, CloudDatabaseStoreInformation ctrCloudDatabaseStoreInformation)
        {
            TridentSitkaConnectionParameters sitkaConnectionParameters = this.connection.SitkaParameters;
            if (sitkaConnectionParameters != null)
            {
                ctrCloudDatabaseStoreInformation.AuthorityId = sitkaConnectionParameters.AuthorityId;
                ctrCloudDatabaseStoreInformation.ContainerId = sitkaConnectionParameters.ContainerId;
                ctrCloudDatabaseAccountInformation.UserName = sitkaConnectionParameters.UserName;
                ctrCloudDatabaseAccountInformation.Password = sitkaConnectionParameters.Password;
            }
        }

        /// <summary>
        /// Populates the UI from trident connection.
        /// </summary>
        /// <param name="ctrWebServiceAccountInformation">The CTR web service account information.</param>
        /// <param name="ctrWebServiceStoreInformation">The CTR web service store information.</param>
        private void PopulateUIFromTridentConnection(WebServiceAccountInformation ctrWebServiceAccountInformation, WebServiceStoreInformation ctrWebServiceStoreInformation)
        {
            TridentWebServiceConnectionParameters webServiceConnectionParameters = this.connection.AmazonParameters;
            if (webServiceConnectionParameters != null)
            {
                ctrWebServiceAccountInformation.AccessKeyId = webServiceConnectionParameters.AccessKey;
                ctrWebServiceAccountInformation.SecretAccessKey = webServiceConnectionParameters.SecretKey;
                ctrWebServiceAccountInformation.IsPublicObject = webServiceConnectionParameters.PublicObjects;
                ctrWebServiceStoreInformation.Bucket = webServiceConnectionParameters.Bucket;
            }
        }

        /// <summary>
        /// Populates the UI from trident connection.
        /// </summary>
        /// <param name="ctrWebService">The CTR web service.</param>
        private void PopulateUIFromTridentConnection(WebServiceConnection ctrWebService)
        {
            WebServiceParameters webServiceParameters = this.connection.WebServiceParameters;
            if (webServiceParameters != null)
            {
                ctrWebService.IsAnonymous = webServiceParameters.IsAnonymous;
                ctrWebService.UserName = webServiceParameters.UserName;
                ctrWebService.Password = webServiceParameters.Password;
                ctrWebService.Url = webServiceParameters.Url.ToString();
            }
        }
       
        #endregion         
                       
        #endregion
    }
}
